<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="模版名称">
                <a-input allowClear placeholder="请输入模版名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="店铺分类">
                <a-select v-model="queryParam.category_id" allowClear>
                  <a-select-option :value="item.id" v-for="item in categoryInfo" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 已启用 </a-radio-button>
          <a-radio-button value="0"> 已禁用 </a-radio-button>
        </a-radio-group>

        <div>
          <a-button type="primary" icon="plus" @click="visible = true">新建 </a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('change', '1')">批量启用</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')">批量禁用</a-menu-item>
              <a-menu-item @click="handleAll('remove')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="list"
        :customRow="customRow"
        :scroll="{ x: 'max-content' }"
        :pagination="{
          total: this.total,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
      >
        <span slot="content" slot-scope="text, record">
          <div class="content">
            <div class="img">
              <a-avatar
                shape="square"
                :size="48"
                icon="user"
                :src="record.home_pic && record.home_pic.length ? record.home_pic[0] : ''"
              />
            </div>

            <div class="txt">
              <h3>{{ record.name }}</h3>
              <p>{{ record.cat_name }}</p>
            </div>
          </div>
        </span>

        <span slot="category_id" slot-scope="text, record">
          {{ getCatName(record.category_id) }}
        </span>

        <span slot="status" slot-scope="text, record">
          <a-badge :color="getStatus(record.status)[1]" :text="getStatus(record.status)[0]" />
        </span>

        <span slot="addtime" slot-scope="text, record">
          {{ record.addtime > 0 ? $moment(record.addtime * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="ewm(record.store_id)">二维码</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.status === '0'"
                ><a href="javascript:;" @click="handleItem('change', record, '1')">启用</a></a-menu-item
              >
              <a-menu-item v-if="record.status === '1'">
                <a href="javascript:;" @click="handleItem('change', record, '0')">禁用</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handleItem('remove', record)">删除</a>
              </a-menu-item>
            </a-menu>
            <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
          </a-dropdown>
          <a-button type="link" @click="onInStore(record)" size="small">进入</a-button>
        </span>
      </a-table>

      <a-modal width="700px" v-model="visible" title="新建模版" ok-text="确认" cancel-text="取消" @ok="onSubmit">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="模版名称" prop="name">
            <a-input v-model="form.name" allowClear />
          </a-form-model-item>
          <a-form-model-item label="模板分类" prop="category_id">
            <a-select v-model="form.category_id" allowClear>
              <a-select-option :value="item.id" v-for="item in categoryInfo" :key="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="选择店铺" prop="from_store_id">
            <a-select
              v-model="form.from_store_id"
              allowClear
              :filter-option="filterOption"
              show-search
              @change="handleSearch"
            >
              <a-select-option :value="item.id" v-for="item in storeList" :key="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="店铺首页截图" prop="home_pic">
            <cyyUploadImg
              @uploadSuccess="(e) => selectPic(e, 'home_pic')"
              @deleteImg="(e) => delPic(e, 'home_pic')"
              :imgList.sync="form.home_pic"
              dataType="list"
              imgSizeText="建议尺寸：1170*2532"
            >
            </cyyUploadImg>
          </a-form-model-item>
          <a-form-model-item label="个人中心截图" prop="center_pic">
            <cyyUploadImg
              @uploadSuccess="(e) => selectPic(e, 'center_pic')"
              @deleteImg="(e) => delPic(e, 'center_pic')"
              :imgList.sync="form.center_pic"
              dataType="list"
              imgSizeText="建议尺寸：1170*2532"
            >
            </cyyUploadImg>
          </a-form-model-item>
          <a-form-model-item label="描述" prop="desc">
            <a-input v-model="form.desc" allowClear type="textarea" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>

    <ContentDetails title="二维码" ref="pop" @cancel="ewmImg = null">
      <img class="ewmImg" :src="ewmImg" alt="" />
    </ContentDetails>
  </page-header-wrapper>
</template>

<script>
import { getQr, templateList, templateAdd, templateDel, templateStatus } from '@/api/saas/copy'
import { getCategoryInfo } from '@/api/store'
import { wechatMpCardList } from '@/api/wechartVipCard'
import { cyyUploadImg } from '@/components/CyyUi/index'
import { generateTokenBySaas } from '@/api/auth'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
  },
  {
    title: '模版信息',
    scopedSlots: {
      customRender: 'content',
    },
    width: 300,
  },
  {
    title: '模版分类',
    scopedSlots: {
      customRender: 'category_id',
    },
  },
  {
    title: '使用次数',
    dataIndex: 'use_count',
    sorter: (a, b) => a.use_count - b.use_count,
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '发布时间',
    dataIndex: 'addtime',
    scopedSlots: {
      customRender: 'addtime',
    },
    sorter: (a, b) => a.addtime - b.addtime,
    width: 200,
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  components: {
    ContentDetails: () => import('@/components/tools/ContentDetail'),
    cyyUploadImg,
  },
  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,
      queryParam: {
        name: '',
        category_id: '',
        status: '-1',
      },
      list: [],
      selectedRowKeys: [],
      categoryInfo: [],
      storeList: [],
      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        category_id: '',
        from_store_id: '',
        home_pic: [],
        center_pic: [],
        desc: '',
      },
      rules: {
        name: [{ required: true, message: '模版名称不能为空', trigger: 'blur' }],
        category_id: [{ required: true, message: '模版分类不能为空', trigger: 'change' }],
        from_store_id: [{ required: true, message: '店铺不能为空', trigger: 'change' }],
        home_pic: [{ required: true, message: '首页截图不能为空', trigger: 'change' }],
        center_pic: [{ required: true, message: '个人中心截图不能为空', trigger: 'change' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
      },

      ewmImg: '',
    }
  },

  async mounted() {
    this.getList()
    this.getCategoryInfo()

    const res = await wechatMpCardList()
    if (res.code == 0) {
      this.storeList = res.store_list || []
    }
  },

  watch: {
    visible(e) {
      if (!e) this.resetForm()
    },
  },

  computed: {
    getCatName() {
      return (id) => {
        let item = this.categoryInfo.find((el) => el.id === id)
        return item ? item.name : ''
      }
    },

    getStatus() {
      return (status) => {
        let text, color
        switch (status) {
          case '1':
            text = '已启用'
            color = '#65C817'
            break

          case '0':
            text = '已禁用'
            color = '#FF4D4F'
            break
        }
        return [text, color]
      }
    },

    isShow() {
      return (is_show) => {
        let item = this.statusList.find((el) => el.id === is_show)
        return item
      }
    },
  },

  methods: {
    onInStore: function (item) {
      generateTokenBySaas({ storeId: item.store_id, username: 'admin' })
        .then((res) => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSaasStore', true)
            storage.set('storeId', item.store_id)
            storage.remove('isPlatform')
            storage.remove('isSupplier')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },
    async ewm(id) {
      const hide = this.$message.loading('加载中', 0)
      const res = await getQr({
        id,
      })
      hide()
      if (!res.code) {
        this.ewmImg = res.data
        this.$refs.pop.visible = true
        return
      }
    },
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const hide = this.$message.loading('加载中', 0)
          let { form } = this
          const res = await templateAdd(form)
          hide()
          if (res.code == 0) {
            this.$message.success('创建成功')
            this.visible = false
            this.getList()
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    selectPic(e, el) {
      e.data.forEach((element) => {
        this.form[el].push(element)
      })
    },

    delPic({ index }, el) {
      this.form[el].splice(index, 1)
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    handleSearch(value) {
      let [item] = this.storeList.filter((d, index) => {
        return d.id == value
      })
      this.form.from_store_id = item.id
    },

    // 获取全部商城分类
    getCategoryInfo() {
      getCategoryInfo({}).then((res) => {
        if (res.code == 0) {
          this.categoryInfo = res.data
        }
      })
    },
    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this
      const res = await templateList({
        ...queryParam,
        pageSize,
        pageNo,
      })
      if (res.code == 0) {
        this.selectedRowKeys = []
        let { totalCount, data } = res.data
        this.total = totalCount
        this.list = data
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 批量操作
    handleAll(type, status) {
      let { selectedRowKeys } = this
      if (!selectedRowKeys.length) {
        this.$message.error('请至少选择一条数据~')
        return
      }

      let ids = selectedRowKeys.join(',')

      switch (type) {
        case 'change':
          this.changeStatus(ids, status)
          break

        case 'remove':
          this.remove(ids)
          break
      }
    },

    // 点击单个
    handleItem(type, item, status) {
      switch (type) {
        case 'change':
          this.changeStatus(item.id, status)
          break

        case 'remove':
          this.remove(item.id)
          break
      }
    },

    // 修改状态
    changeStatus(id, status) {
      templateStatus({
        id,
        status,
      }).then((res) => {
        if (res.code) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
          this.getList()
          this.selectedRowKeys = []
        }
      })
    },

    // 删除接口
    remove(id) {
      templateDel({
        id,
      }).then((res) => {
        if (res.code) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
          this.getList()
          this.selectedRowKeys = []
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

.content {
  display: flex;
  align-items: center;
  height: 48px;
  max-width: 300px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

::v-deep {
  .ant-tag {
    cursor: pointer;
  }
}

.ewmImg {
  display: block;
  width: 300px;
  height: 300px;
  margin: auto;
}
</style>
